<template>
  <div class="container">
    <Headbar />
    <HeadCartBrand title="收银台" showSearchBar="true" />

    <div class="yh-layout-box">
      <div class="order-detail bg-white" v-if="orderDetails">
        <div class="order-head">
          <div class="order-msg" v-if="orderDetails.isCountDown || !payAll">
            <div class="order-icon">
              <img src="@/assets/images/meal/pay-success.png">
            </div>
            <div class="order-tips">
              <p class="yh-text-color bold-title">订单提交成功，请尽快付款！</p>
              <p v-if="!isOrderOver">
                <span v-if="orderType == 2">
                  请尽快完成支付订单款项，过时订单将被自动取消
                </span>
                <span v-else>
                  请在<span class="yh-text-color">{{ countdownText }}</span>小时内完成支付订单款项，过时订单将被自动取消
                </span>

              </p>
              <p v-if="isOrderOver">订单已过期，自动取消</p>
            </div>
          </div>
          <div class="order-pay-all" v-if="payAll">合并支付订单如下：</div>
          <div class="order-money">
            应付金额：￥{{ orderDetails.actualAmount }}
            <span class="retract cursor" @click="clickShowDetail()">
              收起详情
              <span class="triangle-up" v-if="!showDetail"></span>
              <span class="triangle-bottom" v-else></span>
            </span>
          </div>
        </div>

        <div class="order-table" v-if="showDetail">
          <div class="table-head">
            <div class="NO">订单编号</div>
            <div class="info">
              <div class="goodsName">商品名称</div>
              <div class="count">数量</div>
            </div>
            <div class="amount">金额</div>
          </div>
          <div class="table-row" v-for="(item, i) in orderDetails.orderWebDetailDTOList">
            <div class="NO">{{ item.orderNo }}</div>
            <div class="info">
              <div class="item" v-for="(panel, j) in item.orderItemDTOList">
                <div class="goodsName">{{ panel.productName }}</div>
                <div class="count">{{ panel.quantity }}</div>
              </div>
            </div>
            <div class="amount">￥{{ item.payAmount }}</div>
          </div>
        </div>
      </div>

      <div class="order-pay bg-white">
        <div class="pay-head over">
          <div class="pay-money fl" v-if="orderDetails">
            应付金额：<span class="font-red">￥{{ orderDetails.actualAmount }} </span>
          </div>
          <div class="pay-more fr yh-text-color cursor" @click="clickOrderList()">
            查看我的订单 <span>> </span>
          </div>
        </div>
        <div class="pay-type mt-30">
          <ul>
            <li v-for="(i, index) in payType" @click="clickPayType(index)" :class="payTypeActive == index?'cursor active':'cursor'">
              <img :src="i.image">
            </li>
          </ul>
        </div>
        <div class="btn-submit mt-40 cursor pay-now-btn" @click="clickPay()">
          立即支付
        </div>
      </div>
    </div>
    <Footbar />
    <el-dialog
    :close-on-click-modal=false
      title="订单支付"
      :visible.sync="payVisible"
      width="660px"
      :before-close="payClose">
      <div class="over pay-main">
        <div class="pay-qrcode fl">
          <div class="pay-head">
            <img src="@/assets/images/meal/pay-wechat.png" alt="">
            <span>亿万用户的选择，更快更安全</span>
          </div>
          <div class="qrcode">
            <qrcode :value="payQrcode" :options="{ width: 180 }"></qrcode>
          </div>
          <div class="tips">
            <img src="@/assets/images/meal/ewm-tips.png">
          </div>
        </div>
        <div class="pay-images fr">
          <img src="@/assets/images/meal/ewm-img.png">
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Headbar from '@/components/Layouts/Headbar'
import HeadCartBrand from '@/components/Layouts/HeadCartBrand'
import Footbar from '@/components/Layouts/Footbar'
import { orderPayment, cashierOrderDetail, orderPaymentAll, orderPayStatusPc } from '@/api/meal'
import Vue from 'vue';
import VueQrcode from '@chenfengyuan/vue-qrcode';

Vue.component(VueQrcode.name, VueQrcode);

export default {
  name: 'MealCashier',
  components: {
    Headbar,
    HeadCartBrand,
    Footbar,
  },
  data() {
    return {
      payType: [
        {
        type: 'alipay',
        image: require('@/assets/images/meal/pay-ali.png'),
      },
      {
        type: 'wxpay',
        image: require('@/assets/images/meal/pay-wechat.png'),
      }],
      payTypeActive: 0,
      showDetail: true,
      orderDetails: null,
      orderInfo: null,
      payVisible: false,
      payQrcode: null,
      startGetOrderStatus: false,
      productOrderNo: this.getUrlParams('productOrderNo'),
      currentTime: '',
      timer: null,
      countdownText: '',
      payAll: this.getUrlParams('payAll'),//订单列表进来的合并支付
      orderType: this.getUrlParams('orderType'),
      isOrderOver: false,
      stagesNum: this.getUrlParams('stagesNum'),
    }
  },
  created() {
    this.cashierOrderDetail();
  },
  beforeRouteLeave(to, from, next) {
    console.log(to)
    console.log(from)
    if(to.name == 'ConfirmOrder'){
      this.$router.push({
        name: 'CartList'
      })
    }
    next();
  },
  methods: {
    // 获取套餐详情
    cashierOrderDetail() {
      const query = {
        orderNoList: this.productOrderNo
      }
      cashierOrderDetail(query).then(res=>{
        this.orderDetails = res.data;
        if(this.orderType != 2){
          if(res.data.isCountDown || !this.payAll){
            this.currentTime = new Date(this.formatTime(res.data.interfaceDate)).getTime()
            this.countdown(this.formatTime(res.data.overTime))
            clearInterval(this.timer)
            this.timer = setInterval(()=>{
              this.countdown(this.formatTime(res.data.overTime))
            }, 1000);
          }
        }

      })
    },
    payClose() {
      this.payVisible = false;
    },
    // 切换支付类型
    clickPayType(index) {
      this.payTypeActive = index;
    },
    // 显示、隐藏订单
    clickShowDetail() {
      this.showDetail = !this.showDetail
    },
    // 点击支付
    clickPay() {
      if(this.payAll){
        this.orderPaymentAll();
      }else{
        this.orderPayment();
      }
    },
    //成功回调
    successCallback(data) {
      this.startGetOrderStatus = true;
      console.log(data)
      if(data.code == 200){
        if(this.startGetOrderStatus){
          this.orderPayStatusPc()
        }
        // 如果是支付宝，跳转到支付页面
        if(this.payTypeActive == 0){
          const form = data.data.data
          console.log(form)
          const div = document.createElement('div')
          div.id = 'alipayOrder'
          div.innerHTML = form
          document.body.appendChild(div)
          document.querySelector('#alipayOrder').children[0].submit() // 执行后会唤起支付宝
        }else{
          console.log(data.codeURL)
          this.payVisible = true;
          this.payQrcode = data.data.codeURL
        }
      }else{
        this.actionsAfter(data.msg, 'error')
      }
    },
    //订单支付
    orderPayment() {
      orderPayment({
        "type":"order",
        "tradeType":"NATIVE",
        "orderNo": this.productOrderNo,
        "payType": this.payTypeActive == 0?'alipay':'wxpay'
      }).then(res=>{
        this.successCallback(res);
      })
    },
    //合并订单支付
    orderPaymentAll() {
      orderPaymentAll({
        "type":"order",
        "tradeType":"NATIVE",
        "orderNos": this.productOrderNo,
        "payType": this.payTypeActive == 0?'alipay':'wxpay'
      }).then(res=>{
        this.successCallback(res);
      })
    },
    clickOrderList() {

      const h = this.$createElement;
      this.$msgbox({
        title: '提示',
        customClass: 'sales-msgbox',
        message: h('p', null, [
          h('span', null, '是否确认离开收银台？ '),
          h('p', { style: 'color: #999' }, '若确认离开，则订单将进入待付款订单列表，超时未付款订单将被自动取消，请尽快支付。')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.$router.push({
          name: 'MemberOrder'
        })
      }).catch(() => {

      });

    },
    orderPayStatusPc() {
      var that = this;
      var times;

      let orderNo = that.productOrderNo.split(',')[0];

      function interval_fun(){
        orderPayStatusPc({orderNo: orderNo, stagesNum: that.stagesNum }).then(res=>{
          if(res.data){
            that.actionsAfter('支付成功！', 'success')
            clearInterval(times);
            setTimeout(()=>{
              window.location.href = '/mallplus/meal/payStatusOrder?out_trade_no='+orderNo+'&orderType='+that.orderType
            }, 1000)
          }
        })
      };
      times = setInterval(interval_fun, 2000)
    },
    //订单过期倒计时
    countdown(end) {
      let endTime = new Date(end).getTime();
      let difference = endTime - this.currentTime;
      if(difference<0){
        clearInterval(this.timer)
        this.isOrderOver = true;
        return;
      }
      let d = Math.floor(difference/1000/60/60/24);
      let h = Math.floor(difference/1000/60/60%24);
      let m = Math.floor(difference/1000/60%60);
      let s = Math.floor(difference/1000%60);
      this.currentTime = this.currentTime + 1000
      this.countdownText = this.zeroize(h)+':'+this.zeroize(m)+':'+this.zeroize(s)
    },
    formatTime(str) {
      return str.replace(/-/g, '/')
    },
    zeroize(num){
      return num<10?'0'+num:num;
    }
  }
}
</script>
<style lang="scss" scoped>
.order-detail{
  padding: 20px;
  margin-top: 30px;

  .order-head{
    border-bottom: 1px solid #EEEEEE;
    overflow: hidden;
    padding-bottom: 10px;
    position: relative;
  }
  .order-msg{
    float: left;
    overflow: hidden;
    .order-icon{
      float: left;
      img{
        padding-top: 12px;
        vertical-align: middle;
      }
    }
    .order-tips{
      float: left;
      margin-left: 10px;
      p:last-child{
        margin-top: 5px;
        margin-bottom: 0;
      }
      .bold-title{
        font-weight: bold;
        font-size: 18px;
        margin-bottom: 8px;
      }
    }
  }
  .order-money{
    float: right;
    padding-top: 10px;
    font-size: 16px;
    font-weight: 600;
    .retract{
      margin-top: 10px;
      position: absolute;
      right: 0;
      bottom: 0;
      font-size: 14px;
      color: #888888;
      font-weight: 100;
      padding: 8px 12px;
      background: #EEEEEE
    }
  }
  .order-table{
    margin-top: 30px;
    .table-head ,.table-row{
      overflow: hidden;
      margin-top: 10px;
      > div{
        float: left;
        text-align: center;
        padding: 18px 0;
      }
    }
    .table-head{
      background-color: #eee;
      border: 1px solid #DDDDDD;
      color: #888888;
    }
    .table-row{
      color: #666666;
      margin-top: 0;
      border-bottom: 1px solid #eee;
      border-left: 1px solid #eee;
      border-right: 1px solid #eee;
      display: flex;
      justify-content: center;
    }
    .NO{
      width: 20%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .goodsName{
      width: 80%;
    }
    .count{
      width: 20%;
    }
    .amount{
      width: 16%;
    }
    .table-row,.table-head{
      .info{
        width: 64%;
        .item{
          overflow: hidden;
          margin-bottom: 20px;
          &:last-child{
            margin-bottom: 0;
          }
        }
        .goodsName,
        .count{
          float: left;
        }
      }
      .amount{
        float: left;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
.order-pay{
  margin-top: 20px;
  padding: 30px;
  .pay-head{
    padding-bottom: 30px;
    border-bottom: 1px solid #eee;
  }
  .pay-money{
    color: #000000;
    font-size: 16px;
    span{
      font-weight: 600;
    }
  }
  .pay-type{

    overflow: hidden;
    li{
      width: 218px;
      height: 68px;
      text-align: center;
      background: #F7F7F7;
      border: 1px solid #EEEEEE;
      border-radius: 4px;
      margin-right: 30px;
      float: left;
      img{
        margin-top: 17px;
      }
    }
    .active{
      border: 1px solid #255B8B;
      position: relative;
      &::after{
        content: "";
        position: absolute;
        width: 20px;
        height: 20px;
        right: 0;
        bottom: 0;
        z-index: 2;
        background: url('../../assets/images/meal/meal-checked.png');
      }
    }
  }
}
.cursor{
  cursor: pointer;
}
.pay-main .pay-qrcode{
  text-align: center;
  .qrcode{
    width: 186px;
    height: 186px;
    margin: 0 auto;
    border: 1px solid #eee;
    padding: 10px;
    margin-bottom: 20px;
  }
  .pay-head{
    margin-bottom: 20px;
    img{
      vertical-align: middle;
    }
    span{
      vertical-align: middle;
    }
  }
}
.pay-images{
  margin-right: 20px;
}
.order-pay-all{
  font-size: 16px;
  font-weight: 600;
  padding-top: 10px;
  display: inline-block;
  vertical-align: top;
}
.pay-now-btn{
  font-size: 18px;
}
</style>
